//
//  notitestVC.m
//  UIScrollView的快速使用
//
//  Created by hongfei tam on 2019/3/15.
//  Copyright © 2019 YQ05. All rights reserved.
//

#import "notitestVC2.h"
#import "network.h"
#import "MKConstant.h"
#import "DB/DataPersist.h"

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif

#define LocalNotiReqIdentifer    @"LocalNotiReqIdentifer"

@interface notitestVC2 (){
    int LocalNotiint;
}

@end

@implementation notitestVC2

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitle:@"Notification2"];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    CGSize size = self.view.frame.size;
    CGFloat offset = 150;
    NSArray *titles = @[@"发送一个本地通知", @"移除一个本地通知"];
    for (int i=0; i<titles.count; i++) {
        NSString *title = [titles objectAtIndex:i];
        UIButton *btn = [self createCustomButton:title];
        btn.tag = i;
        [self.view addSubview:btn];
        btn.center = CGPointMake(size.width/2, offset);
        offset += btn.frame.size.height+10;
    }
    
    
    network *sendNetWork = [[network alloc]init];
    NSMutableDictionary *senddic = [[NSMutableDictionary alloc]init];
    
    NSString *uid = @"29";
    [senddic setValue:uid forKey:@"uid"];
    
    [sendNetWork GETInfo:YOUNGURL type:@"getSchedule" senddic:senddic savekey:@"getSchedule"]; //发送数据
    
    LocalNotiint = 1;

//    NSString *timestr = @"2019-03-15";
//    NSString *datastr =[NSString stringWithFormat:@"%@年", [timestr substringWithRange:NSMakeRange(0,4)]];
//    NSString *datastr2 =[NSString stringWithFormat:@"%@年", [timestr substringWithRange:NSMakeRange(5,2)]];
//    NSString *datastr3 =[NSString stringWithFormat:@"%@年", [timestr substringWithRange:NSMakeRange(8,2)]];
//    NSLog(@"datastr : %@",datastr );
//    NSLog(@"datastr2 : %@",datastr2 );
//    NSLog(@"datastr3 : %@",datastr3 );


    
    //NSCalendar和NSDateComponents使用
    //        NSCalendar *car = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    //        NSDate *date3 = [NSDate date];
    //        unsigned unit = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit;
    //
    //        NSDateComponents *comp = [car components:unit fromDate:date3];
    //        NSLog(@"现在是%ld年", comp.year);
    //        NSLog(@"现在是%ld月", comp.month);
    //        NSLog(@"现在是%ld日", comp.day);
    //        NSLog(@"现在是%ld时", comp.hour);
    //        NSLog(@"现在是%ld分", comp.minute);
    //        NSLog(@"现在是%ld秒", comp.second);
    
    // Do any additional setup after loading the view.
}

- (UIButton *)createCustomButton:(NSString *)title {
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(0, 0, self.view.frame.size.width-30, 45);
    [btn setTitle:title forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn.layer setBorderColor:[[UIColor lightGrayColor] colorWithAlphaComponent:0.5].CGColor];
    [btn.layer setBorderWidth:1.0];
    [btn.layer setCornerRadius:5.0];
    [btn.layer setMasksToBounds:YES];
    return btn;
}

- (void)btnClicked:(UIButton *)button {
    if (button.tag == 0) {
       NSMutableArray *Schedulearr = [DataPersist readValueNSMutableArray:@"getSchedule"];
          for (int r = 0; r<3; r++) {
                
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                NSMutableDictionary *senddic = [Schedulearr objectAtIndex:0];
                NSLog(@"senddic : %@",senddic);
                
                NSString *str1 = [senddic valueForKey:@"task"];
                NSLog(@"task str1 : %@",str1 );
                
                NSString *str2 = [senddic valueForKey:@"date"];
                NSLog(@"date str2 : %@",str2 );
                
                NSString *str3 = [senddic valueForKey:@"time"];
                NSLog(@"time str3 : %@",str3 );
                
   //             [dic setValue:str1 forKey:@"task"];
              
                NSArray *taskarr = [senddic valueForKey:@"task"];
              
                [dic setValue:[taskarr objectAtIndex:0] forKey:@"task"];
                [dic setValue:str2 forKey:@"date"];
                [dic setValue:str3 forKey:@"time"];
        
                //[dic setValue:@"task11" forKey:@"task"];
//                [dic setValue:@"2019-03-21" forKey:@"date"];
//                [dic setValue:@"16:40:15" forKey:@"time"];
        
                //[self sendLocalNotification:[Schedulearr objectAtIndex:r]];
                 [self sendLocalNotification:dic];
                LocalNotiint = LocalNotiint + 1;
                NSLog(@"LocalNotiint num : %d",LocalNotiint);
            }
       
        
//        [self sendLocalNotification:dic];
    } else if (button.tag == 1) {
        //[self cancelLocalNotificaitons];
         [self cancelLocalNotificaitons2];
    }
}

#pragma mark - 发送一条本地推送通知
- (void)sendLocalNotification:(NSDictionary *)dic {
    
    NSLog(@"sendLocalNotification -> %@",dic);
    
    BOOL testflag = true;
    
    NSString *str1 = @"";
    NSString *str2 = @"";
    NSString *str3 = @"";
    
    if (testflag) {
        
        
        NSArray *taskarr = [dic valueForKey:@"task"];
//        [dic setValue:[taskarr objectAtIndex:0] forKey:@"task"];
        str1 = [taskarr objectAtIndex:0];
        NSLog(@"str1 : %@",str1 );
        
        str2 = [dic valueForKey:@"date"];
        NSLog(@"str2 : %@",str2 );
        
        str3 = [dic valueForKey:@"time"];
        NSLog(@"str3 : %@",str3 );
    }else{
        str1 = [dic valueForKey:@"task"];
        NSLog(@"str1 : %@",str1 );
        
        str2 = [dic valueForKey:@"day"];
        NSLog(@"str2 : %@",str2 );
        
        str3 = [dic valueForKey:@"time"];
        NSLog(@"str3 : %@",str3 );
    }
    
    
    
    NSString *title = @"通知-title";
    NSString *subTitle = @"通知-subtitle";
    NSString *body = str1;//[dic valueForKey:@"task"];//@"通知-body";
    NSInteger badge = 1;
    //NSInteger timeInteval = 5;
    NSDictionary *userInfo = @{@"id":str1};//@{@"id":@"LOCAL_NOTIFY_SCHEDULE_ID"};
    
    /**时间设置 */
    //NSString *day = @"2019-03-15";
    NSString *day = str2;//[dic valueForKey:@"day"];
    NSString *year =[NSString stringWithFormat:@"%@", [day substringWithRange:NSMakeRange(0,4)]];
    NSString *month =[NSString stringWithFormat:@"%@", [day substringWithRange:NSMakeRange(5,2)]];
    NSString *days =[NSString stringWithFormat:@"%@", [day substringWithRange:NSMakeRange(8,2)]];
    NSLog(@"datastr : %@",year );
    NSLog(@"datastr2 : %@",month );
    NSLog(@"datastr3 : %@",days );
    
    //NSString *time = @"16:17:00";
    NSString *time = str3;//[dic valueForKey:@"time"];
    NSString *hours =[NSString stringWithFormat:@"%@", [time substringWithRange:NSMakeRange(0,2)]];
    NSString *minute =[NSString stringWithFormat:@"%@", [time substringWithRange:NSMakeRange(3,2)]];
    NSString *second =[NSString stringWithFormat:@"%@", [time substringWithRange:NSMakeRange(6,2)]];
    NSLog(@"hours : %@",hours );
    NSLog(@"minute : %@",minute );
    NSLog(@"second : %@",second );
    
    /* 时间设置 */
    
    if (@available(iOS 10.0, *)) {
        // 1.创建通知内容
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        //[content setValue:@(YES) forKeyPath:@"shouldAlwaysAlertWhileAppIsForeground"];
        content.sound = [UNNotificationSound defaultSound];
        content.title = title;
        content.subtitle = subTitle;
        content.body = body;
        content.badge = @(badge);
        
        content.userInfo = userInfo;
        
        // 2.设置通知附件内容
        //        NSError *error = nil;
        //        //NSString *path = [[NSBundle mainBundle] pathForResource:@"faphone_BROWN" ofType:@"png"];
        //        //UNNotificationAttachment *att = [UNNotificationAttachment attachmentWithIdentifier:@"att1" URL:[NSURL fileURLWithPath:path] options:nil error:&error];
        //        if (error) {
        //            NSLog(@"attachment error %@", error);
        //        }
        //content.attachments = @[att];
        content.launchImageName = @"banner_b_1500x420-1-1024x287.jpg";
        // 2.设置声音
        UNNotificationSound *sound = [UNNotificationSound defaultSound]; // [UNNotificationSound soundNamed:@"sound01.wav"];// [UNNotificationSound defaultSound];
        content.sound = sound;
        
        
        
        /*重点开始*/
        
        // 3.触发模式 延时
        //UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:timeInteval repeats:NO];
        // 4.设置UNNotificationRequest
        //UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:LocalNotiReqIdentifer content:content trigger:trigger];
        
        // 3.触发模式 定式
        NSDateComponents *components = [[NSDateComponents alloc] init];
        //components.weekday = 4; //周三
        components.year = year.integerValue;
        components.month = month.integerValue;
        components.day = days.integerValue;
        
        components.hour = hours.integerValue; //13点
        components.minute = minute.integerValue;
        components.second = second.integerValue;
        
        
        UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
        
        //UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:LocalNotiReqIdentifer content:content trigger:trigger];
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:str3 content:content trigger:trigger];
        
        //        //这个点，100米范围内，进入触发。
        //        CLLocationCoordinate2D cen = CLLocationCoordinate2DMake(39.990465,116.333386);
        //        CLRegion *region = [[CLCircularRegion alloc] initWithCenter:cen radius:100 identifier:@"center"];
        //        region.notifyOnEntry = YES;
        //        region.notifyOnExit = NO;
        //        UNLocationNotificationTrigger *trigger = [UNLocationNotificationTrigger triggerWithRegion:region repeats:YES];
        /*重点结束*/
        
        
        //5.把通知加到UNUserNotificationCenter, 到指定触发点会被触发
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            NSLog(@"5.把通知加到UNUserNotificationCenter, 到指定触发点会被触发,ID : %@",str3);
        }];
        
        
        
        
        
    } else {
        
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        
        // 1.设置触发时间（如果要立即触发，无需设置）
        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        //        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];// 5 秒之后
        
        // 2.设置通知标题
        localNotification.alertBody = title;
        
        // 3.设置通知动作按钮的标题
        localNotification.alertAction = @"查看";
        
        // 4.设置提醒的声音
        localNotification.soundName = UILocalNotificationDefaultSoundName;// @"sound01.wav";// UILocalNotificationDefaultSoundName;
        
        // 5.设置通知的 传递的userInfo
        localNotification.userInfo = userInfo;
        
        // 6.在规定的日期触发通知
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        // 6.立即触发一个通知
        //[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
    }
}

- (void)cancelLocalNotificaitons {
    NSLog(@"取消一个特定的通知");
    //! 取消一个特定的通知
    NSArray *notificaitons = [[UIApplication sharedApplication] scheduledLocalNotifications];
    //获取当前所有的本地通知
    if (!notificaitons || notificaitons.count <= 0) { return; }
    for (UILocalNotification *notify in notificaitons) {
        if ([[notify.userInfo objectForKey:@"id"] isEqualToString:@"LOCAL_NOTIFY_SCHEDULE_ID"]) {
            if (@available(iOS 10.0, *)) {
                [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[LocalNotiReqIdentifer]];
            } else {
                [[UIApplication sharedApplication] cancelLocalNotification:notify];
            }
            break;
        }
    }
    //! 取消所有的本地通知
    //[[UIApplication sharedApplication] cancelAllLocalNotifications];
}

//. 管理通知
//iOS10的推送都是通过center进行管理的。通过request的identifier，进行通知的查找、更新、删除。这个标识是用来区分这个通知和其他通知的。
//
//更新：center 的 addNotificationRequest:withCompletionHandler: 方法在 id 不变的情况下重新添加，就可以刷新原有的推送。
//删除：
//
//removePendingNotificationRequestsWithIdentifiers:  //删除特定等待递送的通知
//removeAllPendingNotificationRequests  //删除所有等待递送的通知
//removeDeliveredNotificationsWithIdentifiers:  //删除特定已经递送的通知
//removeAllDeliveredNotifications  //删除已经递送的通知
//
//
//查找：
//
//getPendingNotificationRequestsWithCompletionHandler:  //获取所有等待递送的通知
//getDeliveredNotificationsWithCompletionHandler:  //获取所有已经递送的通知
//
//
//作者：liuyanhongwl
//链接：https://www.jianshu.com/p/bb89d636f989
//来源：简书
//简书著作权归作者所有，任何形式的转载都请联系作者获得授权并注明出处。

- (void)cancelLocalNotificaitons2 {
    NSLog(@"删除所有等待递送的通知");

    if (@available(iOS 10.0, *)) {
        [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests]; //删除所有等待递送的通知
        [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];  //删除已经递送的通知
    } else {
        //[[UIApplication sharedApplication] cancelLocalNotification:notify];
    }

}

-(void)getScheduleAction
{
    //接收信息通知
    NSLog(@"接收信息通知");
    [self setScheduleLocalNotification]; //设置本地 日程安排 推送
}
-(void)setScheduleLocalNotification{
    NSMutableArray *Schedulearr = [DataPersist readValueNSMutableArray:@"getSchedule"];
    
    for (NSDictionary *dic in Schedulearr) {
        [self sendLocalNotification:dic];
        LocalNotiint = LocalNotiint + 1;
        NSLog(@"LocalNotiint num : %d",LocalNotiint);
    }
    
//    [self sendLocalNotification:[Schedulearr objectAtIndex:0]];
//    LocalNotiint = LocalNotiint + 1;
//    NSLog(@"LocalNotiint num : %d",LocalNotiint);
    
//    for (int r = 0; r<3; r++) {
//
//        [self sendLocalNotification:[Schedulearr objectAtIndex:r]];
//        LocalNotiint = LocalNotiint + 1;
//        NSLog(@"LocalNotiint num : %d",LocalNotiint);
//    }
}

-(void)viewWillAppear:(BOOL)animated
{
    //接收信息通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getScheduleAction) name:@"getScheduleStatus" object:nil];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    //接受信息 广播 发送成功信息
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"getScheduleStatus" object:nil];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
